<template>
  <div>
    <div class="container">

      <el-form :model="ruleForm1" :disabled="ruleForm1.trialAuthState == 1" :rules="rules1" ref="ruleForm1" label-width="150px" class="form">

        <el-form-item label-width="0" v-if="ruleForm1.trialAuthState == 1">
          <el-alert
            title="待审核"
            type="warning"
            show-icon>
          </el-alert>
        </el-form-item>
        <el-form-item label-width="0" v-if="ruleForm1.trialAuthState == 3">
          <el-alert
            show-icon
            title="审核失败"
            type="warning"
            :description="ruleForm1.trialMsg">
          </el-alert>
        </el-form-item>

        <h2>
          <span>经营执照</span>
          <span class="strong">(*必填)</span>
        </h2>

        <el-form-item label="营业执照" prop="yyImg">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="yyzzSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm1.yyImg" :src="ruleForm1.yyImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="特种行业许" prop="tzhyImg">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="tzhyzSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm1.tzhyImg" :src="ruleForm1.tzhyImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="企业名称" prop="companyName">
                    <el-input v-model="ruleForm1.companyName" placeholder="请输入企业名称" />
                </el-form-item>-->

        <el-form-item label="企业法人" prop="legalPerson"><el-input v-model="ruleForm1.legalPerson" placeholder="请输入企业法人" /></el-form-item>

        <el-form-item label="经营场所" prop="registeredAddress"><el-input v-model="ruleForm1.registeredAddress" placeholder="请输入经营场所" /></el-form-item>

        <!-- <el-form-item label="经营范围" prop="companyScope">
                    <el-input v-model="ruleForm1.companyScope" placeholder="请输入经营范围" />
                </el-form-item>-->

        <!-- <el-form-item label="类型" prop="companyType">
                    <el-input v-model="ruleForm1.companyType" placeholder="请输入类型" />
                </el-form-item>-->

        <el-form-item label="注册号" prop="unifiedCode"><el-input v-model="ruleForm1.unifiedCode" placeholder="请输入注册号" /></el-form-item>
        <el-form-item label="有效期" prop="businessTerm">
          <el-date-picker
            v-model="ruleForm1.businessTerm"
            type="date"
            format="yyyy年MM月dd日"
            value-format="yyyy年MM月dd日"
            placeholder="有效期">
          </el-date-picker>
        </el-form-item>



        <h2>
          <span>个人证件</span>
          <span class="strong">(*必填)</span>
          <el-tag>需与酒店联系人保持一致</el-tag>
        </h2>
        <el-form-item label="身份证照(正面)" prop="sfzImg1">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="sfz1Success"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm1.sfzImg1" :src="ruleForm1.sfzImg1" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>

        <el-form-item label="身份证照(反面)" prop="sfzImg2">

          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="sfz2Success"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm1.sfzImg2" :src="ruleForm1.sfzImg2" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


        <el-form-item label="身份证照(手持)" prop="sfzImg3">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="sfz3Success"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm1.sfzImg3" :src="ruleForm1.sfzImg3" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

          <a @click="showTips = true">详情要求</a>
        </el-form-item>

        <el-form-item label="姓名" prop="sfzName"><el-input v-model="ruleForm1.sfzName" placeholder="请输入身份证姓名" /></el-form-item>

        <el-form-item label="身份证号" prop="idCard"><el-input v-model="ruleForm1.idCard" placeholder="输入身份证号" /></el-form-item>


        <el-row type="flex">
          <el-button v-if="ruleForm1.trialAuthState == 1" disabled>待审核</el-button>
          <el-button v-if="ruleForm1.trialAuthState == 2" type="primary" @click="step2Submit()">{{ $t('Common.Confirm') }}</el-button>
          <el-button v-if="ruleForm1.trialAuthState == 3" type="primary" @click="dataFormSubmit()">重新提交</el-button>
        </el-row>
      </el-form>

      <el-dialog :visible.sync="showMap" title="搜索后选择地址">
        <div class="map-wrap">
          <el-amap-search-box class="map-search" :on-search-result="onSearchResult" :searchOption="{}" />
          <el-amap class="map" :center="mapCenter" :zoom="16">
            <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker" :events="getMarkerEvents()" />
          </el-amap>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="protocol" title="加盟协议"><div class="map-wrap" v-html="hotelProtocol.content"></div></el-dialog>

      <el-dialog :visible.sync="showTips" title="手持身份证拍照要求">
        <img src="../../../../assets/img/idCardSuccess.jpg" />
        <img src="../../../../assets/img/idCardError.jpg" />
        <ul>
          <li>免冠，建议未化妆，五关可见;</li>
          <li>身份证全部信息清晰无遮挡，否则将无法通过认证;</li>
          <li>完整露出手臂;</li>
          <li>以酒店门头招牌为背景图片;</li>
          <li>请勿进行任何软件处理;</li>
          <li>单张图片不超过5M，尺寸要求500（长）X412（宽）以上，支持jpg、png、gif;</li>
        </ul>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data: () => {
    return {
      isSend: false,
      protocol: false,
      hotelProtocol: {},
      timer: 60,
      captchaPath: '',
      editorOption: {
        placeholder: '填写规则：简介中需包含酒店的地理位置、周边信息，店内设施、客房等信息。确保语句通顺、无错别字、段首无空格、不提及星级、无敏感字眼，字数50以上，400以下'
      },
      uploadAction: '',
      active: 0,
      options: [{}],
      props: {
        label: 'name',
        value: 'id',
        children: 'brands'
      },
      ruleForm0: {
        captcha: '',
        uuid: '',
        accept: false,
        smsCode: '',
        linkTel: ''
      },
      rules0: {
        accept: [{ required: true, message: '请同意加盟协议' }],
        linkTel: [{ required: true, message: '请输入酒店联系人电话' }]
      },
      ruleForm: {
        sellerName: '',
        tel: '',
        linkName: '',
        address: '',
        type: '1',
        roomCount: 1,
        brand: '',
        introduction: '',
        facilitatorCode: '',
        invitationCode: '',
        lat: '',
        lng: '',
        coordinates:''
      },
      rules: {
        accept: [{ required: true, message: '请同意加盟协议' }],
        sellerName: [{ required: true, message: '请输入酒店名称' }],
        linkName: [{ required: true, message: '请输入酒店联系人' }],
        tel: [{ required: true, message: '请输入酒店电话' }],
        address: [{ required: true, message: '请选择酒店地址' }],
        coordinates: [{ required: true, message: '经纬度不可为空' }],
        type: [{ required: true, message: '请输入酒店类型' }],
        roomCount: [{ required: true, message: '请输入客房总数' }],
        introduction: [
          { required: true, message: '请输入酒店介绍' },
          {
            validator: (rule, value, callback) => {
              if (value.length < 20 || value.length > 400) {
                return callback(new Error('酒店介绍字数必须20以上，400以下'));
              }
              return callback();
            }
          }
        ]
      },
      ruleForm1: {
        yyImg:'',
        tzhyImg:'',
        sfzImg1:'',
        sfzImg2:'',
        sfzImg3:'',
        sfzName: '',
        idCard: '',
        idCardPicList: [],
        legalPerson: '',
        unifiedCode: '',
        registeredAddress: '',
        businessTerm: '',
        companyIdCardPic: []
      },
      rules1: {
        name: [{ required: true, message: '请输入姓名' }],
        sfzName: [{ required: true, message: '请输入姓名' }],
        idCard: [{ required: true, message: '请输入身份证号' }],
        idCardPicList: [{ required: true, message: '请上传身份证照片' }],
        sfzImg1: [{ required: true, message: '请上传身份证照片' }],
        sfzImg2: [{ required: true, message: '请上传身份证反面照片' }],
        sfzImg3: [{ required: true, message: '请上传手持身份证照片' }],
        // idCardPic: [
        //     { required: true, message: "请上传手持身份证照片" }
        // ],
        // companyName: [{ required: true, message: "请输入企业名称" }],
        legalPerson: [{ required: true, message: '请输入企业法人' }],
        registeredAddress: [{ required: true, message: '请输入企业经营场所' }],
        // companyScope: [
        //     { required: true, message: "请输入企业经营范围" }
        // ],
        // companyType: [{ required: true, message: "请输入企业类型" }],
        unifiedCode: [{ required: true, message: '请输入企业注册号' }],
        companyTime: [{ required: true, message: '请选择企业有效期' }],
        companyIdCardPic: [{ required: true, message: '请上传企业营业执照' }],
        yyImg: [{ required: true, message: '请上传企业营业执照' }]
      },
      markers: [],
      mapCenter: [114.05558, 22.539679],
      showMap: false,
      showTips: false
    };
  },
  activated() {
    this.init();
    this.uploadAction = this.$http.adornUrl('/hotel/common/upload');
    this.fetchhotelBrands();
    this.fetchhotelProtocol();
    if (sessionStorage.getItem('ruleForm') != null) {
      let ruleForm = JSON.parse(sessionStorage.getItem('ruleForm'));
      ruleForm.smsCode = '';
      ruleForm.captcha = '';
      ruleForm.uuid = this.ruleForm.uuid;
      this.ruleForm = ruleForm;
    }
  },
  methods: {
    init() {
      this.$http({
        url: this.$http.adornUrl(`/hotel/hotelseller/store/1`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const hotelSeller = data.hotelSeller || {};
          this.ruleForm1 = {
            id:hotelSeller.id,
            yyImg: hotelSeller.yyImg,
            trialAuthState: hotelSeller.trialAuthState,
            trialMsg: hotelSeller.trialMsg,
            tzhyImg: hotelSeller.tzhyImg,
            legalPerson: hotelSeller.legalPerson,
            registeredAddress: hotelSeller.registeredAddress,
            unifiedCode: hotelSeller.unifiedCode,
            businessTerm: hotelSeller.businessTerm,
            sfzImg1: hotelSeller.sfzImg1,
            sfzImg2: hotelSeller.sfzImg2,
            sfzImg3: hotelSeller.sfzImg3,
            sfzName: hotelSeller.sfzName,
            idCard: hotelSeller.idCard
          };
          this.fileList = this.getImgs(hotelSeller.img);
        }
        this.dataListLoading = false;
      });
    },
    yyzzSuccess(res, file) {
      console.log("res",res)
      console.log("file",file)
      if (res.code == 0) {
        this.ruleForm1.yyImg = res.url
        this.onSuccessCompany(file.raw)
      }
    },
    tzhyzSuccess(res, file) {
      console.log("res",res)
      console.log("file",file)
      if (res.code == 0) {
        this.ruleForm1.tzhyImg = res.url
        // this.onSuccessCompany(file.raw)
      }
    },
    sfz1Success(res, file) {
      console.log("res",res)
      console.log("file",file)
      if (res.code == 0) {
        this.ruleForm1.sfzImg1 = res.url
        this.onSuccessIdCard(file.raw)
      }
    },
    sfz2Success(res, file) {
      console.log("res",res)
      console.log("file",file)
      if (res.code == 0) {
        this.ruleForm1.sfzImg2 = res.url
        // this.onSuccessIdCard(file.raw)
      }
    },
    sfz3Success(res, file) {
      console.log("res",res)
      console.log("file",file)
      if (res.code == 0) {
        this.ruleForm1.sfzImg3 = res.url
        // this.onSuccessIdCard(file.raw)
      }
    },
    coordinatesInput(val) {
      console.log(val)
    },
    //根据地址获取经纬度
    getCoordinates() {
      this.$http({
        url: this.$http.adornUrl(
          `/hotel/common/getCoordinates`
        ),
        method: "get",
        params: this.$http.adornParams({
          "address":this.ruleForm.address
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.ruleForm.coordinates = data.lng + ',' + data.lat;
          this.ruleForm.lat = data.lat
          this.ruleForm.lng = data.lng
          this.$set(this.ruleForm, 'city', data.city);
        }
      });
    },
    async sendSmsCode() {
      await this.checkSellerApply();
      await this.$http({
        url: this.$http.adornUrl('/hotel/common/smsCode'),
        method: 'get',
        params: this.$http.adornParams({
          mobile: this.ruleForm0.linkTel,
          uuid: this.ruleForm0.uuid,
          captchaCode: this.ruleForm0.captcha
        })
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.isSend = true;
            let time = setInterval(() => {
              this.timer -= 1;
              if (this.timer <= 0) {
                clearInterval(time);
                this.isSend = false;
              }
            }, 1000);
          } else {
            this.$message.error(data.msg);
            this.getCaptcha();
          }
        })
    },
    // 获取验证码
    getCaptcha() {
      this.ruleForm0.uuid = getUUID();
      this.captchaPath = this.$http.adornUrl(`/captcha.jpg?uuid=${this.ruleForm0.uuid}`);
    },
    onEditorBlur() {},
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
    },
    fetchhotelBrands() {
      this.$http({
        url: this.$http.adornUrl('/hotel/seller/hotelBrands'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.data;
        }
        console.log(data);
      });
    },
    fetchhotelProtocol() {
      this.$http({
        url: this.$http.adornUrl('/hotel/hotelprotocol/info/3'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.hotelProtocol = data.hotelProtocol;
        }
      });
    },
    checkSellerApply() {
      this.$http({
        url: this.$http.adornUrl('/hotel/seller/checkSellerApply'),
        method: 'get',
        params: this.$http.adornParams({
          tel: this.ruleForm0.linkTel,
          type: 1
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const seller = data.data;
          this.ruleForm0 = {
            ...this.ruleForm0,
            linkTel: seller.linkTel
          };
          this.ruleForm = {
            ...this.ruleForm,
            sellerName: seller.name,
            linkName: seller.linkName,
            tel: seller.tel,
            address: seller.address,
            type: seller.star + '',
            roomCount: 1,
            introduction: seller.introduction,
            lat: seller.lat,
            lng: seller.lng
          };
          this.ruleForm1 = {
            sfzName: seller.sfzName,
            idCard: seller.idCard,
            idCardPicList: [],
            legalPerson: seller.legalPerson,
            unifiedCode: seller.unifiedCode,
            businessTerm: seller.businessTerm,
            registeredAddress: seller.registeredAddress,
            companyIdCardPic: []
          };
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    step2Submit() {
      this.$refs.ruleForm1.validate(valid => {
        if (!valid) {
          return false;
        }
        this.$http({
          url: this.$http.adornUrl(`/hotel/hotelseller/authUpdate`),
          method: 'post',
          data: this.$http.adornData({
            ...this.ruleForm1
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.init();
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500,
              onClose: () => {

              }
            });
            sessionStorage.removeItem('ruleForm');
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;

      pois.forEach(poi => {
        let { lng, lat } = poi;
        lngSum += lng;
        latSum += lat;
        this.markers.push([poi.lng, poi.lat]);
      });
      let center = {
        lng: lngSum / pois.length,
        lat: latSum / pois.length
      };
      this.mapCenter = [center.lng, center.lat];
    },
    getMarkerEvents() {
      return {
        click: ({ lnglat }) => {
          const host = 'https://restapi.amap.com/v3/geocode/regeo';
          axios.get(`${host}?location=${lnglat.lng},${lnglat.lat}&key=61da46f8202196bd6a794a0fd70d8a9b`).then(res => {
            if (!this.ruleForm.address) {
              this.$set(this.ruleForm, 'address', res.data.regeocode.formatted_address);
            }
            if (Array.isArray(res.data.regeocode.addressComponent.city)) {
              this.$set(this.ruleForm, 'city', res.data.regeocode.addressComponent.province);
            } else {
              this.$set(this.ruleForm, 'city', res.data.regeocode.addressComponent.city);
            }
            this.$set(this.ruleForm, 'lat', lnglat.lat);
            this.$set(this.ruleForm, 'lng', lnglat.lng);
            this.$set(this.ruleForm, 'coordinates', lnglat.lng + "," + lnglat.lat);
            this.showMap = false;
          });
        }
      };
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    onSuccessIdCard(file) {
      const formData = new FormData();
      formData.append('file', file);
      this.$http({
        url: this.$http.adornUrl('/hotel/facilitator/parse-id-card'),
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.ruleForm1 = {
            ...this.ruleForm1,
            ...data.idCardInfo,
            sfzName: data.idCardInfo.name
          };
        } else {
        }
      });
    },
    onSuccessCompany(file) {
      const formData = new FormData();
      formData.append('file', file);
      this.$http({
        url: this.$http.adornUrl('/hotel/facilitator/parse-license'),
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.ruleForm1.legalPerson = data.license.legalPerson;
          this.ruleForm1.registeredAddress = data.license.registeredAddress;
          this.ruleForm1.unifiedCode = data.license.unifiedCode;
          this.ruleForm1.businessTerm = data.license.businessTerm;
        } else {
        }
      });
    },
    onIdCardPicListFileChange(index, file, fileList) {
      const list = fileList.filter(item => item.status === 'success').map(item => item.response.url);
      const idCardPicList = this.ruleForm1.idCardPicList;
      idCardPicList[index] = list[0];
      this.$set(this.ruleForm1, 'idCardPicList', idCardPicList.filter(value => !!value));
    },
    onIdCardPicFileChange(file, fileList) {
      const list = fileList.filter(item => item.status === 'success').map(item => item.response.url);
      this.$set(this.ruleForm1, 'idCardPic', list);
    },
    onCompanyIdCardPicFileChange(index, file, fileList) {
      const list = fileList.filter(item => item.status === 'success').map(item => item.response.url);
      const idCardPicList = this.ruleForm1.companyIdCardPic;
      idCardPicList[index] = list[0];
      this.$set(this.ruleForm1, 'companyIdCardPic', idCardPicList.filter(value => !!value));
    },
    onExceed(file, fileList) {
      this.$message.error(`最多上传${fileList.length}张`);
    }
  }
};
</script>

<style lang="scss">
.container {
  margin: 0 auto;
  width: 1200px;
  .login-captcha {
    img {
      max-width: 100%;
      height: 34px;
    }
  }
  .steps {
    margin: 20px 0;
  }

  .form {
    width: 800px;
  }

  .map-wrap {
    position: relative;

    .map {
      height: 400px;
    }

    .map-search {
      position: absolute;
      left: 20px;
      top: 20px;
    }
  }

  .strong {
    color: red;
  }
}
</style>
